const DEV_MODE = 0;

var model = [];

// 训练模型
function inModel(srcArr, type) {
    let count = 0;
    for (var i = 0; i < srcArr.length; i++) {
        for (var j = 0; j < srcArr[i].length; j++) {
            if (srcArr[i][j]) count++;
        }
    }
    for (var i = 0; i < srcArr.length; i++) {
        for (var j = 0; j < srcArr[i].length; j++) {
            if (srcArr[i][j]) addMid2Model(i, j, type, count);
        }
    }
}

// 模型 中间层
function addMid2Model(i, j, type, count) {
    if (!model[i]) {
        model[i] = [];
    } else {
        if (!model[i][j]) {
            let nDic = {};
            nDic[type] = 1/count;
            model[i][j] = nDic;
        } else {
            addOne(model[i][j], type, 1/count)
        }
    }
}

// 调用模型
function getType(testArr) {
    let scoreDic = {};
    let finalChoice = '';
    let finalScore = 0;
    for (var i = 0; i < testArr.length; i++) {
        for (var j = 0; j < testArr[i].length; j++) {
            if (testArr[i][j]) getScore(i, j, scoreDic);
        }
    }
    for (var type in scoreDic) {
        if (scoreDic[type] > finalScore) {
            finalChoice = type;
            finalScore = scoreDic[type];
        }
    }
    log(finalChoice, scoreDic);
    return finalChoice;
}

// 获取分数
function getScore(i, j, scoreDic) {
    for (var type in model[i][j]) {
        addOne(scoreDic, type, model[i][j][type])
    }
}

// 给对象加值
function addOne(src, key, num) {
    if (src[key]) {
        src[key] += num;
    } else {
        src[key] = num;
    }
}

let srcData = require('./data/demo1.json')
// 拿一部分数据去训练模型
let modelData = srcData.splice(0, srcData.length * .75 | 0)
modelData.forEach(ele=>{
    inModel(ele.data, ele.type);
})

log(model)
print(`训练集【${formatStr(modelData.length, 5, {ph: '0'})}】`);

// 剩下的那些数据
let testData = srcData;

// 测试模型
function testModel(testData) {
    let count = 0; 
    let succ = 0;
    testData.forEach(ele=>{
        let result = getType(ele.data);
        count++;
        if (result == ele.type) {
            succ++;
        }
    })
    return succ/count
}

function log(...msg) {
    if (DEV_MODE) {
        console.log(...msg)
    }
}
function print(msg) {
    console.log(msg)
}
function formatStr(msg, len, config={}) {
    let tarStr = '';
    msg = msg.toString();
    for (var i = 0; i<len; i++) {
        tarStr += config.ph || ' ';
    }
    if (config.ph == 'left') {
        return (msg + tarStr).substr(0, len); 
    } else {
        return (tarStr + msg).substr(msg.length, len);
    }
}

print(`测试集【${formatStr(testData.length, 5, {ph: '0'})}】 成功率：${(testModel(testData)*100).toFixed(2)}% `);